<template>
  <div class="instances">
    <div class="page-header">
      <h2>实例管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>创建实例
      </el-button>
    </div>

    <el-card>
      <el-table
        v-loading="loading"
        :data="instances"
        style="width: 100%"
      >
        <el-table-column prop="name" label="实例名称" />
        <el-table-column prop="node.name" label="所属节点" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="资源配置">
          <template #default="{ row }">
            <div>CPU: {{ row.cpu_cores }}核</div>
            <div>内存: {{ row.memory_gb }}GB</div>
            <div>磁盘: {{ row.disk_gb }}GB</div>
          </template>
        </el-table-column>
        <el-table-column prop="created_by" label="创建者" />
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="editInstance(row)">编辑</el-button>
              <el-button size="small" type="success" @click="showResourceUsage(row)">监控</el-button>
              <el-button size="small" type="danger" @click="deleteInstance(row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑实例对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑实例' : '创建实例'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="实例名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="所属节点" prop="node">
          <el-select v-model="form.node" placeholder="请选择节点">
            <el-option
              v-for="node in nodes"
              :key="node.id"
              :label="node.name"
              :value="node.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="CPU核心数" prop="cpu_cores">
          <el-input-number v-model="form.cpu_cores" :min="1" />
        </el-form-item>
        <el-form-item label="内存(GB)" prop="memory_gb">
          <el-input-number v-model="form.memory_gb" :min="1" />
        </el-form-item>
        <el-form-item label="磁盘(GB)" prop="disk_gb">
          <el-input-number v-model="form.disk_gb" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 资源使用监控对话框 -->
    <el-dialog
      v-model="monitorVisible"
      title="资源使用监控"
      width="800px"
    >
      <div ref="chartRef" style="height: 400px"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { useCloudStore } from '../stores/cloud'

const store = useCloudStore()
const loading = ref(false)
const dialogVisible = ref(false)
const monitorVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const chartRef = ref(null)
let chart = null

const form = ref({
  name: '',
  node: '',
  cpu_cores: 1,
  memory_gb: 1,
  disk_gb: 1
})

const rules = {
  name: [
    { required: true, message: '请输入实例名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  node: [
    { required: true, message: '请选择所属节点', trigger: 'change' }
  ],
  cpu_cores: [
    { required: true, message: '请输入CPU核心数', trigger: 'blur' }
  ],
  memory_gb: [
    { required: true, message: '请输入内存大小', trigger: 'blur' }
  ],
  disk_gb: [
    { required: true, message: '请输入磁盘大小', trigger: 'blur' }
  ]
}

const instances = ref([])
const nodes = ref([])

onMounted(async () => {
  await Promise.all([fetchInstances(), fetchNodes()])
})

async function fetchInstances() {
  loading.value = true
  try {
    await store.fetchInstances()
    instances.value = store.instances
  } catch (error) {
    ElMessage.error('获取实例列表失败')
  } finally {
    loading.value = false
  }
}

async function fetchNodes() {
  try {
    await store.fetchNodes()
    nodes.value = store.nodes
  } catch (error) {
    ElMessage.error('获取节点列表失败')
  }
}

function getStatusType(status) {
  const types = {
    running: 'success',
    stopped: 'info',
    error: 'danger'
  }
  return types[status] || 'info'
}

function getStatusText(status) {
  const texts = {
    running: '运行中',
    stopped: '已停止',
    error: '错误'
  }
  return texts[status] || status
}

function showCreateDialog() {
  isEdit.value = false
  form.value = {
    name: '',
    node: '',
    cpu_cores: 1,
    memory_gb: 1,
    disk_gb: 1
  }
  dialogVisible.value = true
}

function editInstance(instance) {
  isEdit.value = true
  form.value = { ...instance }
  dialogVisible.value = true
}

async function deleteInstance(instance) {
  try {
    await ElMessageBox.confirm(
      `确定要删除实例 "${instance.name}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // TODO: 实现删除实例的逻辑
    ElMessage.success('删除成功')
    await fetchInstances()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

async function showResourceUsage(instance) {
  monitorVisible.value = true
  try {
    await store.fetchResourceUsage(instance.id)
    const usageData = store.resourceUsage
    
    // 初始化图表
    if (!chart) {
      chart = echarts.init(chartRef.value)
    }
    
    const option = {
      title: {
        text: `${instance.name} 资源使用趋势`
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['CPU使用率', '内存使用率', '磁盘使用率']
      },
      xAxis: {
        type: 'time',
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [
        {
          name: 'CPU使用率',
          type: 'line',
          data: usageData.map(item => [item.timestamp, item.cpu_usage])
        },
        {
          name: '内存使用率',
          type: 'line',
          data: usageData.map(item => [item.timestamp, item.memory_usage])
        },
        {
          name: '磁盘使用率',
          type: 'line',
          data: usageData.map(item => [item.timestamp, item.disk_usage])
        }
      ]
    }
    
    chart.setOption(option)
  } catch (error) {
    ElMessage.error('获取资源使用数据失败')
  }
}

async function submitForm() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    // TODO: 实现创建/更新实例的逻辑
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    dialogVisible.value = false
    await fetchInstances()
  } catch (error) {
    ElMessage.error('表单验证失败')
  }
}
</script>

<style scoped>
.instances {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}
</style> 